/**
 * @Description: 主页面
 * @Copyright: 2017 www.fallsea.com Inc. All rights reserved.
 * @author: fallsea
 * @version 1.6.1
 * @License：MIT
 */

layui.use(['layer','fsTab',"element","form"], function(){
	var element = layui.element;
	var fsTab = layui.fsTab;
	var form = layui.form;
	intiCompanySelect();

	//初始化显示菜单
	showMenu($("#fsTopMenu li.layui-this").attr("dataPid"));

	window.addEventListener("hashchange", hashChanged, false);

	hashChanged();

    initCurrentMenu();
    
	   


	function intiCompanySelect(){
		$("#showBasicInfo").click(function(){
			layer.open({
				  type: 1
				  ,title: '公司信息' //不显示标题栏
				  ,closeBtn: false
				  ,area: ['500px', '300px']
				  ,shade: 0.8
				  ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
				  ,resize: false
				  ,btn: ['修改', '取消']
				  ,btnAlign: 'c'
				  ,moveType: 1 //拖拽模式，0或者1
				  ,content: $("#coreOrgExpand")
				  ,yes: function(index,layero){
				  	//获取表单信息
                    var serializeObj = {};
                    $("#coreOrgExpand").find('input').each(function () {
                        serializeObj[this.name] = this.value;
                    });
                    // 关闭弹窗
                    layer.close(index);
                    Common.post("/updateOrgInfo.json",serializeObj,function(rps){
                        //window.location.href = Common.ctxPath +"/";
                        Common.info("信息更新成功!")

                    })
					  //window.location.href=Common.ctxPath+"/updateOrgInfo.do?orgInfo="+JSON.stringify(serializeObj);
				  }
				});
		});
		
		$("#changePassword").click(function(){
			layer.open({
				  type: 1
				  ,title: '修改密码' //不显示标题栏
				  ,closeBtn: false
				  ,area: ['500px', '250px']
				  ,shade: 0.8
				  ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
				  ,resize: false
				  ,btn: ['修改', '取消']
				  ,btnAlign: 'c'
				  ,moveType: 1 //拖拽模式，0或者1
				  ,content: $("#coreOrgPassword")
				  ,yes: function(index,layero){
				  	//获取表单信息
                  var serializeObj = {};
                  $("#coreOrgPassword").find('input').each(function () {
                      serializeObj[this.name] = this.value;
                  });
                  if(!serializeObj["password"]||!serializeObj["password2"]){
                	  Common.fail("请输入要修改的密码！");
   	                return false;
                  }
                  if(serializeObj["password"]!=serializeObj["password2"]){
                	  Common.fail("两次输入密码不一致！");
   	                return false;
                  }
                  if(serializeObj["oldPassword"]!=serializeObj["currentUserPassword"]){
                	  Common.fail("原密码不正确！");
   	                return false;
                  }
                  
                  // 关闭弹窗
                  layer.close(index);
                  Common.post("/changePassword.json",serializeObj,function(rps){
                      //window.location.href = Common.ctxPath +"/";
                      Common.info("密码修改成功!")

                  })
					  //window.location.href=Common.ctxPath+"/updateOrgInfo.do?orgInfo="+JSON.stringify(serializeObj);
				  }
				});
		});
		$("#gotoMessage").click(function(){
			var currentUserId=$("#currentUserId").val();
			 $.ajax({
			   		url:Common.ctxPath+'/message/quoteMessage/selectMessage.json',
						type:"POST",
						data:{"userId":currentUserId},
						dataType:'json',
						success:function(data){
						//	console.log(data.data);
							var contentHtml = "<div class='layui-container' name='messagelist'  style='width: 800px;color:#333333;font-size: 14px;'>" ;
							contentHtml+="<div class='layui-row'  style=''>&emsp;</div>";
							contentHtml+="<div class='layui-row'  style=''><a id='deleteAllMessage'>全部删除</a>&emsp;&emsp;<a id='readedAllMessage'>全部已读</a></div>";
							if(data.data){
								for(var i=0;i<data.data.length;i++){
									contentHtml+="<div class='layui-row'>&ensp;</div>";
									contentHtml+="<div class='layui-row' style='height:28px;font-size: 16px;font-weight:bold;'>"+(data.data[i].messageType=="xitong"?"系统消息":(data.data[i].messageType=="jiangfa"?"奖罚消息":"营销消息"))+"</div>";
									contentHtml+="<div class='layui-row'>"+data.data[i].displayDate+"</div>";
									contentHtml+="<div class='layui-row'>"+data.data[i].content+"</div>";
									contentHtml+="<hr class='layui-bg-gray'>";
								}	
							}
							contentHtml+="</div>";
							 layer.open ({
								   type: 1,
								   title: "消息列表",
								   offset:'rt',
								 //  fixed:false,
								 //  top:100,
								   area: ['800px', '800px'],
								 //  btn: ['确定', '取消'],
								   content: contentHtml,
								   success: function(){
									  $("#deleteAllMessage").click(function(){
										  Common.post("/message/quoteMessageUser/deleteAll.json",{"userId":currentUserId},function(){
											  layer.closeAll();
							                })
									  });
									  $("#readedAllMessage").click(function(){
										  Common.post("/message/quoteMessageUser/readedAll.json",{"userId":currentUserId},function(){
											  layer.closeAll();
							                })
									  });
								   },
								   yes: function () {
									   layer.closeAll();
								   }
							 });
						},
						error:function(data){
							console.log("err:"+ data)
						}
					})
			
			
		});
		
		
	}

	function hashChanged(){
        //获取路由信息
		var hash = window.location.hash;
		if(!$.isEmpty(hash) && hash.length>1){
			var menuId = hash.substring(1);
			//获取layId
			var dom = $('#fsLeftMenu a[menuId="'+ menuId +'"]').parent();
			if(dom.length>0){
				var layId = dom.attr("lay-id");
				if($.isEmpty(layId)){
					layId = $.uuid();
					dom.attr("lay-id",layId);
					fsTab.add(dom.find("a").html(),dom.find("a").attr("dataUrl"),layId);
				}
				fsTab.tabChange(layId);

				fsTab.menuSelectCss(layId);
			}
		}
	}


	$("#fsTopMenu li").bind("click",function(){
		var dataPid = $(this).attr("dataPid");
		var url = $('#url'+dataPid).val();
		if(url.indexOf("skip/erpSystem") > -1){
			window.location.href = Common.ctxPath + url;
		}
		showMenu(dataPid);
	});


	//显示菜单
	function showMenu(dataPid){
		if(!$.isEmpty(dataPid)){
			$('#fsLeftMenu>li').hide();
			$('#fsLeftMenu>li[dataPid="'+ dataPid +'"]').show();
		}
	}

    function initCurrentMenu() {
        var currentMenu = $(".initMenu").val();
        var orderId = $(".orderId").val();//订单号
        var itemId = $(".itemId").val();//订单明细ID
        var userAccessoryId = $(".userAccessoryId").val();//原文件ID
        if(currentMenu){
            var dom = $('#fsLeftMenu a[menuId="'+ currentMenu +'"]').parent();
            if(dom.length>0){
            	//点击nav
                var dataPid =  dom.parents('li').attr('dataPid');
                $('#fsTopMenu li[dataPid="'+ dataPid +'"]').click();
                showMenu(dataPid);

                //点击左侧菜单
                var layId = dom.attr("lay-id");
                if($.isEmpty(layId)){
                    layId = $.uuid();
                    dom.attr("lay-id",layId);
                    var dataUrl = dom.find("a").attr("dataUrl");
					if (!$.isEmpty(orderId) && !$.isEmpty(itemId)){
                        dataUrl += "?orderId="+ orderId +"&itemId="+ itemId +"&userAccessoryId="+ userAccessoryId;
					}
                    fsTab.add(dom.find("a").html(),dataUrl,layId);
                }
                fsTab.tabChange(layId);

                fsTab.menuSelectCss(layId);
            }
        }
    }

	//渲染tab
	fsTab.render();

	//新增tab
	function addTab(title,dataUrl,layId){
		fsTab.add(title,dataUrl,layId);
	}

	//手机设备的简单适配
	var treeMobile = $('.site-tree-mobile'),
	shadeMobile = $('.site-mobile-shade')

	treeMobile.on('click', function(){
		$('body').addClass('site-mobile');
	});

	shadeMobile.on('click', function(){
		$('body').removeClass('site-mobile');
	});


	//菜单绑定

	$(".fsSwitchMenu").on("click",function(){
		if($(this).find("i.icon-category").length>0){
			$(this).find("i").removeClass("icon-category").addClass("icon-viewgallery");
		}else{
			$(this).find("i").removeClass("icon-viewgallery").addClass("icon-category");
		}
		$(".layui-layout-admin").toggleClass("showMenu");
	});

});